package org.springperu.aop.demo.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springperu.aop.demo.model.Customer;
import org.springperu.aop.demo.service.AuditService;
import org.springperu.aop.demo.service.CustomerService;

@Controller
@RequestMapping(value="/customer/*/**")
public class CustomerController  {
	@Autowired
	CustomerService customerService;
	
	@Autowired
	AuditService auditService;
	
	@RequestMapping(value="/customer/load", method=RequestMethod.GET)
	public ModelAndView load(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView("customer_form");
	}
	
	@RequestMapping(value="/customer/save", method=RequestMethod.POST)
	public ModelAndView saveCustomer(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Customer customer = new Customer();		
		ServletRequestDataBinder binder = new ServletRequestDataBinder(customer);
		binder.bind(request);
		customerService.saveCustomer(customer);
		
		List<Map<String, Object>> customers = customerService.getAllCustomers();
 		List<Map<String, Object>> audits = auditService.getAllAudits();
 		HashMap model = new HashMap();
 		model.put("customers", customers);
 		model.put("audits", audits);
		return new ModelAndView("customer_saved",model);
	}
}
